﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Carbon.Web.Forms.jQueryForms
{
    public class FileUploadEditor : Carbon.Web.Forms.Controls.FileUploadEditor
    {
        protected override IEditor CreateEditor()
        {
            FileUploadEditorLayout layout = (FileUploadEditorLayout)this.Page.LoadControl(PathUtility.Join(Configuration.Instance.ControlsPath, "FileUploadEditorLayout.ascx", '/'));
            layout.FileUploadEditor = this;

            return layout;
        }

        
        private bool m_RenderValidationFailed = default(bool);
        private bool RenderValidationFailed
        {
            get
            {
                return m_RenderValidationFailed;
            }
            set
            {
                m_RenderValidationFailed = value;
            }
        }

        private ApplicationException m_ErrorExceptionDuringUpdateModel = default(ApplicationException);
        public ApplicationException ErrorExceptionDuringUpdateModel
        {
            get
            {
                return m_ErrorExceptionDuringUpdateModel;
            }
            set
            {
                m_ErrorExceptionDuringUpdateModel = value;
            }
        } 
        
        private bool m_ErrorDuringUpdateModel = default(bool);
        private bool ErrorDuringUpdateModel
        {
            get
            {
                return m_ErrorDuringUpdateModel;
            }
            set
            {
                m_ErrorDuringUpdateModel = value;
            }
        }

        public override void OnUpdateModel(object sender, UpdateModelEventArgs args)
        {
            try
            {
                base.OnUpdateModel(sender, args);
            }
            catch (ApplicationException ex)
            {
                this.IsValid = false;
                this.ErrorDuringUpdateModel = true;
                this.ErrorExceptionDuringUpdateModel = ex;
            }
        }

        public override void OnUpdateControl(object sender, UpdateControlEventArgs args)
        {
            base.OnUpdateControl(sender, args);

            RenderValidationFailed = !CalculateIsValid();
        }

        public override void RenderControl(System.Web.UI.HtmlTextWriter writer)
        {
            jQueryFormsViewControlBase.RenderBoxes(writer, RenderValidationFailed, true, RenderValidationFailed ? Errors.AtLeastOneFileMustBeUploaded : string.Empty, () =>
                {
                    base.RenderControl(writer);
                });
        }
    }
}
